package cn.wolfcode.web.modules.visitinfo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.custlinkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.custlinkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.orderinfo.entity.TbOrderInfo;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.visitinfo.entity.TbVisit;
import cn.wolfcode.web.modules.visitinfo.service.ITbVisitService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @author haiyang
 * @since 2022-10-11
 */
@Controller
@RequestMapping("visitinfo")
public class TbVisitController extends BaseController {

    @Autowired
    private ITbVisitService entityService;
    @Autowired
    private ITbCustomerService customerService;
    @Autowired
    private ITbCustLinkmanService custLinkmanService;

    private static final String LogModule = "TbVisit";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);

        mv.setViewName("visit/visitinfo/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('visit:visitinfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("visit/visitinfo/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('visit:visitinfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("visit/visitinfo/update");
        TbVisit visit = entityService.getById(id);
        mv.addObject("obj", visit);
        mv.addObject("id", id);
        List<TbCustomer> custList = customerService.list();
        mv.addObject("custs", custList);
        List<TbCustLinkman> linkmanList = custLinkmanService.lambdaQuery()
                .eq(TbCustLinkman::getCustId,visit.getCustId()).list();
        mv.addObject("linkmans",linkmanList);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('visit:visitinfo:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String custId,String linkmanId,String visitType,String start, String end) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (!org.springframework.util.StringUtils.isEmpty(start)&&!org.springframework.util.StringUtils.isEmpty(end)) {
            startTime = LocalDateTime.parse(start, formatter);
            endTime = LocalDateTime.parse(end, formatter);
        }
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page = entityService.lambdaQuery()
                .like(!StringUtils.isEmpty(parameterName),TbVisit::getVisitReason,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbVisit::getContent,parameterName)
                .eq(!StringUtils.isEmpty(custId),TbVisit::getCustId,custId)
                .eq(!StringUtils.isEmpty(linkmanId),TbVisit::getLinkmanId,linkmanId)
                .eq(!StringUtils.isEmpty(visitType),TbVisit::getVisitType,visitType)
                .between(!org.springframework.util.StringUtils.isEmpty(start)&&!org.springframework.util.StringUtils.isEmpty(end), TbVisit::getVisitDate, startTime, endTime)
                .page(page);

        List<TbVisit> records = page.getRecords();
        for (TbVisit record:records) {
            String customerName = customerService.getById(record.getCustId()).getCustomerName();
            record.setCustomerName(customerName);
            String linkmanName = custLinkmanService.getById(record.getLinkmanId()).getLinkman();
            record.setLinkmanName(linkmanName);
        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('visit:visitinfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbVisit entity, HttpServletRequest request) {
        entity.setInputTime(LocalDateTime.now());

        SysUser loginUser = (SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUser(loginUser.getUserId());//录入人

        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('visit:visitinfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbVisit entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('visit:visitinfo:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @RequestMapping("export")
    @SysLog(value = LogModules.EXPORT, module = LogModule)
    public void export(String parameterName,String custId,String linkmanId,String visitType,String start, String end, HttpServletResponse response) {
        List<TbVisit> records = exportCommon(parameterName, custId,linkmanId, visitType, start, end);
        ExportParams exportParams = new ExportParams();
        //样式、字节码、内容
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbVisit.class, records);
        try {
            PoiExportHelper.exportExcel(response, "拜访管理", workbook);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private List<TbVisit> exportCommon(String parameterName,String custId,String linkmanId,String visitType,String start, String end) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (!org.springframework.util.StringUtils.isEmpty(start)&&!org.springframework.util.StringUtils.isEmpty(end)) {
            startTime = LocalDateTime.parse(start, formatter);
            endTime = LocalDateTime.parse(end, formatter);
        }

        List<TbVisit> records = entityService.lambdaQuery()
                .like(!StringUtils.isEmpty(parameterName),TbVisit::getVisitReason,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbVisit::getContent,parameterName)
                .eq(!StringUtils.isEmpty(custId),TbVisit::getCustId,custId)
                .eq(!StringUtils.isEmpty(linkmanId),TbVisit::getLinkmanId,linkmanId)
                .eq(!StringUtils.isEmpty(visitType),TbVisit::getVisitType,visitType)
                .between(!org.springframework.util.StringUtils.isEmpty(start)&&!org.springframework.util.StringUtils.isEmpty(end), TbVisit::getVisitDate, startTime, endTime)
                .list();

        for (TbVisit record:records) {
            String customerName = customerService.getById(record.getCustId()).getCustomerName();
            record.setCustomerName(customerName);
            String linkmanName = custLinkmanService.getById(record.getLinkmanId()).getLinkman();
            record.setLinkmanName(linkmanName);
        }
        return records;
    }
}
